/**
  ******************************************************************************
  * @file    TCP_ConnServer.c
  * @author  Eng. Eletricista Andre L. A. Lopes
  * @version V1.0.0
  * @date    segunda, 22 de dezembro de 2014
  * @brief   Função para abrir um socket Stream Socket.
  ******************************************************************************
  * @attention
  *
  * 					e-mail: andrelopes.al@gmail.com.
  *
  ******************************************************************************
  */

/** @addtogroup TCP
  * @{
  */

/* Includes ------------------------------------------------------------------*/
#include "../../exatron/inc/common.h"


Socket_t sock;

int main(int argc, char *argv[])
{
	socklen_t clilen;
    int n=0;
    int yes=1;

    if(argc < 2)
    {
        printf("\nUso: dg_server Porta\r\n\n");
        return 1;
    }

    bzero((char *)&sock.seraddr,sizeof(sock.seraddr));

    sock.serfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock.serfd < 0)
    {
    	exit(1);
    }

    sock.seraddr.sin_port = htons(atoi(argv[1]));
    sock.seraddr.sin_family = AF_INET;
    sock.seraddr.sin_addr.s_addr = INADDR_ANY;	// Pŕoprio IP

    if(setsockopt(sock.serfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1)
    {
    	printf("Error on setsockopt\n\r");
    	exit(1);
    }

    if(bind(sock.serfd,(struct sockaddr *)&sock.seraddr,sizeof(sock.seraddr))<0)
    {
    	printf("Error on binding\n\r");
    	exit(1);
    }

    clilen = sizeof(struct sockaddr);

    fcntl(sock.serfd, F_SETFL, O_NONBLOCK);

    while(1)
    {
    	bzero(sock.Data.buf_rx,RX_BUF_LEN);
    	n = 0;
    	printf("\r\nEsperando por conexao...\r\n");
    	do
    	{
    		n = recvfrom(sock.serfd,sock.Data.buf_rx,RX_BUF_LEN,0,(struct sockaddr *)&sock.cliaddr,&clilen);
    	}while(n == -1);

    	printf("\r\nConectou com %s\r\n", inet_ntoa(sock.cliaddr.sin_addr));

    	printf("Recebi: %s\r\n", sock.Data.buf_rx);

    	n = 0;
    	while(n < strlen(sock.Data.buf_rx))
    	{
    		n += sendto(sock.serfd,sock.Data.buf_rx,strlen(sock.Data.buf_rx),0,(struct sockaddr *)&sock.cliaddr,clilen);
    	}
    }
    close(sock.serfd);

    return 0;
}








